import { useRouter, useRoute } from "vue-router";
import { showLoading, closeLoading } from "@/utils/vant";
import { customAlphabet } from "nanoid";
import { queryNewsDtl } from "@/api/chkNum";

export default function useFetchNewsDtl(id?: string | number) {
  const nanoid = customAlphabet(
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
    16
  );
  const resData = ref<any>({});
  const router = useRouter();
  const route = useRoute();
  const advertIds: any = ref([]);

  const gennerateWrap = () => {
    const divToInsert = document.createElement("div");
    divToInsert.id = nanoid(16);
    advertIds.value.push(divToInsert.id);
    divToInsert.className = "center w-full";
    return divToInsert;
  };

  const insertDivsPeriodically = (node: any, interval: any) => {
    let currentCharCount = 0;
    function traverse(node: any) {
      if (node.nodeType === Node.TEXT_NODE) {
        const text = node.nodeValue;
        currentCharCount += text.length;
      } else if (node.nodeType === Node.ELEMENT_NODE) {
        for (const child of node.childNodes) {
          traverse(child);
        }
      }
      if (currentCharCount >= interval) {
        const div = gennerateWrap().cloneNode(true);
        node.parentNode.insertBefore(div, node.nextSibling);
        currentCharCount = 0;
      }
    }
    traverse(node);
  };

  const fetchData = async () => {
    try {
      if (!route.params.id && !id) return;
      showLoading();
      const res: any = await queryNewsDtl((id || route.params.id) as string);
      resData.value = res?.data?.list?.[0] ?? {};
      nextTick(() => {
        const container = document.getElementById("RichTextWrapId");
        if (container) {
          insertDivsPeriodically(container, 600);
        }
      });
    } finally {
      closeLoading();
    }
  };

  onBeforeMount(() => {
    window.scrollTo(0, 0);
  });

  onMounted(() => {
    fetchData();
  });

  return {
    resData,
    advertIds,
    route,
    router
  };
}
